package logic

import (
	"context"
	"doctor-package/models/cache"
	"doctor-package/models/mysql"
	"encoding/json"
	"time"

	"doctor-package/packagerpc/internal/svc"
	"doctor-package/packagerpc/packagerpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type ListUserLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewListUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ListUserLogic {
	return &ListUserLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *ListUserLogic) ListUser(in *packagerpc.ListUserRequest) (*packagerpc.ListUserResponse, error) {
	// todo: add your logic here and delete this line

	var user []mysql.User
	mysql.DB.Debug().Find(&user)

	result, _ := cache.Rdb.Get(l.ctx, "userList").Result()

	if result == "" {
		marshal, _ := json.Marshal(user)

		cache.Rdb.Set(l.ctx, "userList", marshal, time.Hour*1)
	} else {
		json.Unmarshal([]byte(result), &user)
	}

	var userList []*packagerpc.ListUser

	for _, m := range user {
		list := packagerpc.ListUser{
			Account: m.Account,
			Id:      int64(m.ID),
		}
		userList = append(userList, &list)
	}

	return &packagerpc.ListUserResponse{List: userList}, nil
}
